package com.huarui.department.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.xwork.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.ewaf.framework.action.BaseAction;
import org.ewaf.framework.model.ListModel;
import org.ewaf.framework.util.HttpUtil;

import com.huarui.department.model.Department;
import com.huarui.department.model.DepartmentListModel;
import com.huarui.department.service.DepartmentService;
import com.huarui.initial.action.InitialAction;
import com.huarui.store.action.StoreListModel;
import com.huarui.store.model.Store;
import com.huarui.user.model.SessionMessage;
import com.huarui.user.security.UserHolder;
import com.huarui.util.PinyinToolkit;

/**
 * xzz
 * @author Administrator
 *
 */
@SuppressWarnings("serial")
public class DepartmentAction extends BaseAction {
	private final static Logger logger = Logger.getLogger(DepartmentAction.class);
	private DepartmentService departmentService;

	private String dir;
	private String sort;
	private int start;
	private int limit;
	private String keyword;
	private SessionMessage sessionMessage;
	private Map<String,Object> resultMap=new HashMap<String, Object>();
	
	

	public Map<String, Object> getResultMap() {
		return resultMap;
	}

	public void setDepartmentService(DepartmentService departmentService) {
		this.departmentService = departmentService;
	}

	
	
	public String getKeyword() {
		return keyword;
	}

	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}

	public String getDir() {
		return dir;
	}

	public void setDir(String dir) {
		this.dir = dir;
	}

	public String getSort() {
		return sort;
	}

	public void setSort(String sort) {
		this.sort = sort;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public SessionMessage getSessionMessage() {
		return sessionMessage;
	}

	public void setSessionMessage(SessionMessage sessionMessage) {
		this.sessionMessage = sessionMessage;
	}

	public String index() {

		sessionMessage = UserHolder.getCurrentSessionMessage();

		return "index";
	}

	@SuppressWarnings("unchecked")
	public String query() {
		sessionMessage = UserHolder.getCurrentSessionMessage();
		DepartmentListModel lm = getModelUtil(httpServletRequest);

		Integer companyId = sessionMessage.getCompanyId();
		ListModel<Department> listModel=null;
		try {
			listModel = departmentService.getDepartmentsByCondition(lm, companyId);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		JSONArray root = JSONArray.fromObject(listModel.getResult());
		// 分页信息
		resultMap.put("totalProperty", listModel.getTotal());
		resultMap.put("root", root);

		return "json";
	}

	public String findByCompanyId() {
		try {
			
		
		SessionMessage sm = UserHolder.getCurrentSessionMessage();
		
		Integer companyId = sm.getCompanyId();
		
		ListModel<Department> lm = new ListModel<Department>();
		
		lm.setPageSize(limit);
		
		lm.setStart(start);
		
		ListModel<Department> listModel = departmentService.getDepartmentsBycompanyId(lm,companyId,keyword);

		JSONArray root = JSONArray.fromObject(listModel.getResult());	
		
		resultMap.put("root", root);
		resultMap.put("totalProperty", listModel.getTotal());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "json";
	}

	@SuppressWarnings("unchecked")
	public String save() {

		sessionMessage = UserHolder.getCurrentSessionMessage();

		Integer companyId = sessionMessage.getCompanyId();

		HttpServletRequest request = HttpUtil.getRequest();

		String jsonAll = request.getParameter("jsonAll");

		JSONObject jsonObject = JSONObject.fromObject(jsonAll);

		Department department = (Department) JSONObject.toBean(jsonObject,
				Department.class);


		
		if (department.getId()!= null){
			
            Map map = new HashMap();	
			map.put("name", department.getName());
			map.put("companyId",companyId);
			
			Department d = departmentService.getByName(map);
			if(d!=null){
				if(!department.getId().equals(d.getId())){
	     	    resultMap.put("failure", "部门名称不能重复");
	     	    return "json";
						
			  }
			}
			
		try{
				
			Department dm=(Department)departmentService.getById(department.getId());	
			dm.setCompanyId(companyId);
			dm.setName(department.getName());
			dm.setPyCode(PinyinToolkit.cn2FirstSpell(dm
					.getName()));
			departmentService.update(dm);
			}catch (Exception e) {
				logger.error("部门更新出错", e);
         	    resultMap.put("failure", "更新失败");
         	    return "json";
			}

		} else {

			Map map = new HashMap();			
			map.put("name", department.getName());
			map.put("companyId",companyId);
			
			Department d = departmentService.getByName(map);
			if(d!=null){
				
	     	    resultMap.put("failure", "部门名称不能重复");
	     	    return "json";
						
			}
			
			
		try{
            Map m= new HashMap();
			
			m.put("name", department.getName());
			m.put("companyId",companyId);
			
			Department dp = departmentService.getByName(m);
			if(dp!=null){
				
				
				dp.setIsDelete(0);
				departmentService.update(dp);
				
			}else{
						
			department.setCompanyId(companyId);

			department.setPyCode(PinyinToolkit.cn2FirstSpell(department
					.getName()));

			departmentService.create(department);
			
			
			}
		  }catch (Exception e) {
			  logger.error("部门增加出错", e);
            resultMap.put("failure", "保存失败");
			  
		    return "json";
		}

		}

		resultMap.put("success", "OK");
		resultMap.put("department", department);
		return "json";
	}

	public String delete() throws IOException {

		HttpServletRequest request = HttpUtil.getRequest();

		String id = request.getParameter("id");

		HttpServletResponse response = ServletActionContext.getResponse();

		response.setContentType("text/plain; charset=UTF-8");// 处理中文问题的必须的代码

		if (id != null) {

			Integer storeId = Integer.valueOf(id);

			try {

				Department department = (Department) departmentService
						.getById(storeId);

				department.setIsDelete(1);

				departmentService.update(department);

			} catch (Exception e) {

				resultMap.put("failure", "删除失败");
				
				return "json";
			}

		} else {

			 resultMap.put("failure", "该对象不存在");
			 
			 return "json";

		}

		return null;

	}
	
	public String revertDepartment() throws IOException {

		HttpServletRequest request = HttpUtil.getRequest();

		String id = request.getParameter("id");

		if (id != null) {

			Integer storeId = Integer.valueOf(id);

			try {

				Department department = (Department) departmentService
						.getById(storeId);

				department.setIsDelete(0);

				departmentService.update(department);

			} catch (Exception e) {

				resultMap.put("failure", "更新失败");
				
				return "json";
			}

		} else {

			 resultMap.put("failure", "该对象不存在");
			 
			 return "json";

		}

		return null;
	}
	
	private DepartmentListModel getModelUtil(HttpServletRequest request) {
		
		DepartmentListModel departmentListModel=new DepartmentListModel();
		departmentListModel.setPageSize(limit);
		departmentListModel.setStart(start);
		departmentListModel.setOrderBy(sort);
		departmentListModel.setDesc(dir.equalsIgnoreCase("desc") ? true : false);
		String jsonAll = request.getParameter("jsonAll");
		
		if (StringUtils.isNotBlank(jsonAll)) {

			JSONObject jsonObject = JSONObject.fromObject(jsonAll);
			
			departmentListModel.setIsDelete(jsonObject.getString("isDelete"));
			
		}
				
		return departmentListModel;
	}

}
